import { GameStateManager } from './managers/GameStateManager'
import { ResourceManager } from './managers/ResourceManager'
import { GameScene } from './scenes/GameScene'
import { LobbyScene } from './scenes/LobbyScene'
import { ResultScene } from './scenes/ResultScene'
import { SettingsScene } from './scenes/SettingsScene'
import { GameUtils } from './utils/GameUtils'
import { PerformanceMonitor } from './utils/PerformanceMonitor'
import { PerformanceTestScene } from './scenes/PerformanceTestScene'

export class Game {
  constructor(canvas) {
    this.canvas = canvas
    this.ctx = canvas.getContext('2d')
    this.width = canvas.width
    this.height = canvas.height
    
    // 初始化游戏状态管理器
    this.stateManager = new GameStateManager()
    
    // 初始化资源管理器
    this.resourceManager = new ResourceManager()
    
    // 初始化游戏模式和资源
    this.gameMode = 'friend'
    this.backgrounds = {
      friend: 'images/backgrounds/friend/friend_bg.png',
      couple: 'images/backgrounds/couple/couple_bg.png'
    }
    this.questionBanks = {
      friend: [], // 朋友模式问题库
      couple: []  // 情侣模式问题库
    }
    
    // 初始化 Worker
    this.initWorker()
    
    // 初始化游戏场景
    this.initScenes()
    
    // 初始化游戏循环
    this.lastTime = 0
    this.accumulator = 0
    this.timeStep = 1000 / 60 // 60 FPS
    
    // 初始化性能监控
    this.performanceMonitor = new PerformanceMonitor()
    
    // 绑定更新方法
    this.update = this.update.bind(this)
  }
  
  // 初始化 Worker
  initWorker() {
    try {
      // 创建 Worker
      this.worker = wx.createWorker('workers/gameWorker.js')
      
      // 监听 Worker 消息
      this.worker.onMessage(this.onWorkerMessage.bind(this))
      
      console.log('Worker initialized successfully')
    } catch (error) {
      console.error('Failed to initialize worker:', error)
    }
  }
  
  // 处理 Worker 消息
  onWorkerMessage(message) {
    console.log('Received message from worker:', message)
    
    // 处理 Worker 返回的结果
    if (message.type === 'result') {
      // 这里可以添加处理 Worker 结果的逻辑
      console.log('Worker task result:', message.data)
    }
  }
  
  // 向 Worker 发送任务
  sendTaskToWorker(taskData) {
    if (this.worker) {
      this.worker.postMessage({
        type: 'task',
        data: taskData
      })
    } else {
      console.error('Worker not initialized')
    }
  }
  
  // 初始化所有游戏场景
  initScenes() {
    // 注册游戏场景
    this.stateManager.registerScene('lobby', new LobbyScene(this))
    this.stateManager.registerScene('game', new GameScene(this))
    this.stateManager.registerScene('result', new ResultScene(this))
    this.stateManager.registerScene('settings', new SettingsScene(this))
    this.stateManager.registerScene('performance_test', new PerformanceTestScene(this))
    
    // 设置初始场景
    this.stateManager.switchScene('performance_test') // 直接启动性能测试
  }
  
  // 启动游戏
  async start() {
    try {
      // 开始记录资源加载时间
      this.performanceMonitor.startResourceLoad('backgrounds')
      
      // 加载背景图片
      await this.loadBackgrounds()
      
      // 结束记录资源加载时间
      this.performanceMonitor.endResourceLoad('backgrounds')
      
      // 初始化游戏状态
      this.stateManager.init()
      
      // 播放背景音乐
      this.resourceManager.playBGM()
      
      // 开始游戏循环
      requestAnimationFrame(this.update)
    } catch (error) {
      console.error('游戏启动失败:', error)
      // 这里可以添加错误提示UI
    }
  }
  
  // 游戏主循环
  update(timestamp) {
    // 记录帧渲染
    this.performanceMonitor.recordFrame()
    
    // 计算时间增量
    const deltaTime = timestamp - this.lastTime
    this.lastTime = timestamp
    
    // 累积时间
    this.accumulator += deltaTime
    
    // 固定时间步长更新
    while (this.accumulator >= this.timeStep) {
      this.fixedUpdate()
      this.accumulator -= this.timeStep
    }
    
    // 渲染
    this.render()
    
    // 继续游戏循环
    requestAnimationFrame(this.update)
  }
  
  // 固定时间步长更新
  fixedUpdate() {
    const currentScene = this.stateManager.getCurrentScene()
    if (currentScene) {
      currentScene.update()
    }
  }
  
  // 渲染
  render() {
    // 清空画布
    this.ctx.clearRect(0, 0, this.width, this.height)
    
    // 渲染当前场景
    const currentScene = this.stateManager.getCurrentScene()
    if (currentScene) {
      currentScene.render(this.ctx)
    }
  }
  
  // 获取游戏状态管理器
  getStateManager() {
    return this.stateManager
  }
  
  // 获取资源管理器
  getResourceManager() {
    return this.resourceManager
  }
  
  // 获取画布上下文
  getContext() {
    return this.ctx
  }
  
  // 获取画布尺寸
  getSize() {
    return {
      width: this.width,
      height: this.height
    }
  }
  
  // 销毁游戏
  destroy() {
    // 销毁 Worker
    if (this.worker) {
      this.worker.terminate()
    }
    
    // 销毁资源管理器
    this.resourceManager.destroy()
    
    // 停止性能监控
    this.performanceMonitor.stopMonitoring()
  }

  setGameMode(mode) {
    this.gameMode = mode
  }

  getGameMode() {
    return this.gameMode
  }

  getCurrentQuestionBank() {
    return this.questionBanks[this.gameMode]
  }

  getCurrentBackground() {
    const bg = this.backgrounds[this.gameMode]
    return bg || null // 如果背景加载失败，返回null使用默认背景
  }

  // 加载背景图片
  async loadBackgrounds() {
    try {
      const loadPromises = Object.entries(this.backgrounds).map(async ([mode, path]) => {
        try {
          const image = await this.resourceManager.loadImage(path)
          this.backgrounds[mode] = image
        } catch (error) {
          console.error(`加载${mode}模式背景失败:`, error)
          // 使用默认背景
          this.backgrounds[mode] = null
        }
      })
      
      await Promise.all(loadPromises)
      console.log('背景图片加载完成')
    } catch (error) {
      console.error('背景图片加载失败:', error)
      throw error
    }
  }

  // 切换场景
  switchScene(fromScene, toScene) {
    const endTransition = this.performanceMonitor.recordSceneTransition(fromScene, toScene)
    this.stateManager.switchScene(toScene)
    endTransition()
  }

  // 获取性能报告
  getPerformanceReport() {
    return this.performanceMonitor.getPerformanceReport()
  }
} 